﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;

using ClientDependency.Core;
using Our.Umbraco.DataType.Markdown.Extensions;

[assembly: WebResource("Our.Umbraco.DataType.Markdown.Resources.PageDown.Markdown.Converter.js", "application/x-javascript")]
[assembly: WebResource("Our.Umbraco.DataType.Markdown.Resources.PageDown.Markdown.Sanitizer.js", "application/x-javascript")]
[assembly: WebResource("Our.Umbraco.DataType.Markdown.Resources.PageDown.Markdown.Editor.js", "application/x-javascript")]
[assembly: WebResource("Our.Umbraco.DataType.Markdown.Resources.Scripts.WmdControl.js", "application/x-javascript")]
[assembly: WebResource("Our.Umbraco.DataType.Markdown.Resources.Styles.ContentEditor.css", "text/css", PerformSubstitution = true)]
[assembly: WebResource("Our.Umbraco.DataType.Markdown.Resources.PageDown.wmd-buttons.png", "image/png")]

namespace Our.Umbraco.DataType.Markdown
{
	/// <summary>
	/// The WMD control for the Markdown Editor.
	/// </summary>
	public class WmdControl : WebControl, INamingContainer
	{
	    /// <summary>
		/// Gets or sets the options.
		/// </summary>
		/// <value>The options.</value>
		public Options Options { get; set; }

		/// <summary>
		/// Gets or sets the text.
		/// </summary>
		/// <value>The text for the TextBoxControl.</value>
		public string Text
		{
			get
			{
				return this.TextBoxControl.Text;
			}

			set
			{
				if (this.TextBoxControl == null)
				{
					this.TextBoxControl = new TextBox();
				}

				this.TextBoxControl.Text = value;
			}
		}

        /// <summary>
        /// Gets or sets the ButtonBar control.
        /// </summary>
        /// <value>The ButtonBar control.</value>
        protected Panel ButtonBarControl { get; set; }

		/// <summary>
		/// Gets or sets the TextBox control.
		/// </summary>
		/// <value>The TextBox control.</value>
		protected TextBox TextBoxControl { get; set; }

        /// <summary>
        /// Gets or sets the preview control.
        /// </summary>
        /// <value>
        /// The preview control.
        /// </value>
        protected Panel PreviewControl { get; set; }

		/// <summary>
		/// Initialize the control, make sure children are created
		/// </summary>
		/// <param name="e">An <see cref="T:System.EventArgs"/> object that contains the event data.</param>
		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);

			this.EnsureChildControls();
		}

		/// <summary>
		/// Add the resources (styles/scripts)
		/// </summary>
		/// <param name="e">The <see cref="T:System.EventArgs"/> object that contains the event data.</param>
		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			// Check if WMD Editor has been enabled.
			if (this.Options.EnableWmd)
			{
				// adds the client dependencies.
				this.AddResourceToClientDependency("Our.Umbraco.DataType.Markdown.Resources.Styles.ContentEditor.css", ClientDependencyType.Css);
                this.AddResourceToClientDependency("Our.Umbraco.DataType.Markdown.Resources.PageDown.Markdown.Converter.js", ClientDependencyType.Javascript);
                this.AddResourceToClientDependency("Our.Umbraco.DataType.Markdown.Resources.PageDown.Markdown.Sanitizer.js", ClientDependencyType.Javascript);
                this.AddResourceToClientDependency("Our.Umbraco.DataType.Markdown.Resources.PageDown.Markdown.Editor.js", ClientDependencyType.Javascript);
                this.AddResourceToClientDependency("Our.Umbraco.DataType.Markdown.Resources.Scripts.WmdControl.js", ClientDependencyType.Javascript);
			}
		}

		/// <summary>
		/// Called by the ASP.NET page framework to notify server controls that use composition-based implementation to create any child controls they contain in preparation for posting back or rendering.
		/// </summary>
		protected override void CreateChildControls()
		{
			base.CreateChildControls();

			this.EnsureChildControls();

			// create the controls
            this.ButtonBarControl = new Panel
                {
                    ID = "wmd-button-bar-" + this.ClientID,
                    CssClass = "wmd-button-bar",
                    ClientIDMode = ClientIDMode.Static
                };

		    this.TextBoxControl.ID = "wmd-input-" + this.ClientID;
            this.TextBoxControl.ClientIDMode = ClientIDMode.Static;
			this.TextBoxControl.TextMode = TextBoxMode.MultiLine;
			this.TextBoxControl.Height = Unit.Pixel(this.Options.Height);
			this.TextBoxControl.Width = Unit.Pixel(this.Options.Width);
			this.TextBoxControl.CssClass = "wmd-input umbEditorTextFieldMultiple";

		    this.PreviewControl = new Panel()
		        {
                    ID = "wmd-preview-" + this.ClientID,
		            ClientIDMode = ClientIDMode.Static,
		            CssClass = "wmd-preview"
		        };

			// add the controls
            this.Controls.Add(this.ButtonBarControl);
			this.Controls.Add(this.TextBoxControl);
            this.Controls.Add(this.PreviewControl);
		}

		/// <summary>
		/// Renders the contents of the control to the specified writer. This method is used primarily by control developers.
		/// </summary>
		/// <param name="writer">A <see cref="T:System.Web.UI.HtmlTextWriter"/> that represents the output stream to render HTML content on the client.</param>
		protected override void RenderContents(HtmlTextWriter writer)
		{
            writer.AddAttribute(HtmlTextWriterAttribute.Class, "wmd-panel");
            writer.AddAttribute(HtmlTextWriterAttribute.Style, string.Concat("width: ", this.Options.Width + 6, "px;"));
            writer.RenderBeginTag(HtmlTextWriterTag.Div);

            this.ButtonBarControl.RenderControl(writer);
			this.TextBoxControl.RenderControl(writer);
            this.PreviewControl.RenderControl(writer);

            writer.RenderEndTag();

			// check if WMD Editor has been enabled.
			if (this.Options.EnableWmd)
			{
			    var pagedownScript =
			        string.Format(
			            @"$('#wmd-input-{0}').pagedown({{enableSanitizing:'{1}',previewMode:'{2}',helpUrl:'{3}'}});", 
                        this.ClientID,
                        this.Options.EnableSanitizing,
                        this.Options.SelectedPreview,
                        this.Options.HelpUrl);

                var javascript = string.Concat("<script type='text/javascript'>", "$(function() {", pagedownScript, "});", "</script>");

				writer.WriteLine(javascript);
			}
		}
	}
}
